import Vue from 'vue'
import VueRouter from 'vue-router'
import LoginView from '../views/LoginView.vue'  // 直接加载所有组件

Vue.use( VueRouter )

const routes = [
  {
    path: '/',
    name: 'index',
    // component: LoginView
    redirect: "/login"  // 重定向
  },
  {
    path: '/login',
    name: 'login',
    meta: { title: '登录' },
    component: LoginView
  },
  {
    path: "/home",
    props: true,  // 使用后，路由的params参数，可以在对应组件里面，通过props来获取, 把this.$route.param中得属性，映射到props里面。
    name: "home",
    meta: { title: 'HOME页面' },
    // 懒加载组件： 当访问/home时，才加载组件：
    component: () => import( "../views/HomeView.vue" ),
    // beforeEnter ( to, from, next ) {
    //   // 限制访问/home得来源，
    //   if ( from.fullPath === "/login" ) {
    //     next()
    //   } else {
    //     next( "/login" )
    //   }
    // },
    children: [
      {
        path: "", // 配置一个默认子路由，
        meta: { title: 'HOME页面' },

        component: () => import( "../components/AccessLayer.vue" )
      },
      {
        path: "about",
        meta: { title: '关于' },
        // name: "about",
        // 懒加载组件： 当访问/home时，才加载组件：
        component: () => import( "../views/AboutView.vue" ),
        children: [
          {
            path: 'aboutgs',
            meta: { title: '关于公司' },
            component: () => import( "../views/AboutGs.vue" ),
          },
          {
            path: 'aboutwh',
            meta: { title: '公司文化' },

            component: () => import( "../views/AboutWh.vue" ),
          },
          {
            path: '',
            meta: { title: '关于' },

            component: () => import( "../views/AboutWh.vue" ),
          },

        ]
      },
      {
        path: "product",
        name: "product",
        meta: { title: '产品' },

        // 懒加载组件： 当访问/home时，才加载组件：
        component: () => import( "../views/ProductView.vue" ),
        // components: {
        //   'view1': '组件1'，
        //   'view2': '组件2'，
        // }
      },
      {
        path: "product/:pid",
        name: "product2",
        meta: { title: '产品详细' },

        // 懒加载组件： 当访问/home时，才加载组件：
        component: () => import( "../views/ProductView.vue" )
      },
      {
        path: "order",
        name: "order",
        meta: { title: '订单' },

        // 懒加载组件： 当访问/home时，才加载组件：
        component: () => import( "../views/OrderView.vue" )
      },
    ]

  },

]

const router = new VueRouter( {
  mode: 'history',
  base: process.env.BASE_URL,
  routes
} )

router.beforeEach( ( to, from, next ) => {
  // console.log( to )
  // console.log( from )
  // next()
  // 登录权限得验证
  let isLogin = sessionStorage.getItem( "isLogin" );
  if ( isLogin === '1' || to.fullPath === "/login" ) {
    next()
  } else {
    next( "/login" )
  }

} )

router.afterEach( ( to, from ) => {
  console.log( to )
  document.title = to.meta.title;  // 修改页面得title。
} )



export default router
